package com.shanghaionstar.nav.presenter;

import android.content.Intent;
import android.content.res.Resources;

import com.onstar.cn.auth.userProfile.FeatureEnum;
import com.onstar.cn.common.exception.HttpException;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.common.util.DeviceUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.IMVPView;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.ErrorInfo;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.nav.iview.INavFavListSimpleView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.PoiHistoryInfo;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.nav.service.NavService;
import com.shanghaionstar.sqlite.SearchHistoryImpl;
import com.shanghaionstar.sqlite.TBTHistoryImpl;
import com.shanghaionstar.sqlite.UserAddressInfoImpl;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.AuthorUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.ErrorCodeUtil;
import com.shanghaionstar.utils.FinalConfigParams;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.LoadCityList;
import com.shanghaionstar.utils.NavHolder;

import java.util.List;

import rx.Subscription;
import rx.functions.Action1;
import rx.subscriptions.Subscriptions;

/**
 * Created by 6335yz on 2016/7/7.
 */
public class NavSearchFavSimpleListPresenter extends BasePresenter {

    private AbstractMapActivity mapActivity;
    private INavFavListSimpleView navFavListSimpleView;
    private NavService navService;
    private Resources res;
    protected Subscription deleteSubscription = Subscriptions.empty();
    private UserAddressInfoImpl userAddressInfoImpl;

    @Override
    public void setView(IMVPView view) {
        super.setView(view);
        navFavListSimpleView = (INavFavListSimpleView) view;
    }

    public NavSearchFavSimpleListPresenter(IMVPScheduler mvpScheduler, AbstractMapActivity mapActivity) {
        super(mvpScheduler);
        this.mapActivity = mapActivity;
        navService = new NavService(mapActivity);
        res = mapActivity.getResources();
        userAddressInfoImpl = new UserAddressInfoImpl(mapActivity);

    }


    public void sendTbtOrOdd(final PoiItemInfo poiItemInfo) {
        if(ApplicationUtil.getInstance().isCommanding){
            ApplicationUtil.getInstance().controlCommand(mapActivity);
            return;
        }else {
            ApplicationUtil.getInstance().isCommanding = true;
        }
        NavInfoModel navInfoModel = new NavInfoModel();
        if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
            if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
            } else if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
            }
        } else {
            navInfoModel.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
        }
        navInfoModel.poiItemInfo = poiItemInfo;
        if (validateTbtOrOdd(poiItemInfo, navInfoModel.remoteCommandsType)) {
            new AuthorUtil().reauthForNoPin(mapActivity, new Action1() {
                @Override
                public void call(Object o) {
                    NavInfoModel tmp = new NavInfoModel();
                    if (BusinessUtil.isServiceFeature(FeatureEnum.SENDNAVDESTINATION.value(), mapActivity)) {
                        if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.TBT_CHOOSE_SAVE, true)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                        } else if (PreferencesUtls.getInstance(mapActivity).getBoolean(FinalConstants.SharedPreferencesConfig.ODD_CHOOSE_SAVE, false)) {
                            tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_NAV_DESTINATION;
                        }
                    } else {
                        tmp.remoteCommandsType = RemoteCommandsType.COMMANDS_TBT_ROUTE;
                    }
                    tmp.poiItemInfo = poiItemInfo;
                    doNavCommand(tmp);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    ApplicationUtil.getInstance().isCommanding =false;
                    if (navFavListSimpleView != null) {
                        ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException(mapActivity, new HttpException("", throwable.getMessage()));
                        navFavListSimpleView.onResponseError(new OnStarException("", errorInfo.getMsg()));
                    }
                }
            });
        }
    }


    private boolean validateTbtOrOdd(PoiItemInfo poiItemInfo, RemoteCommandsType remoteCommandsType) {
        if (poiItemInfo == null) return false;
        if (remoteCommandsType != RemoteCommandsType.COMMANDS_TBT_ROUTE && remoteCommandsType != RemoteCommandsType.COMMANDS_NAV_DESTINATION)
            return false;
        if (!ApplicationUtil.getInstance().isLogin())
            return false;
        if (ApplicationUtil.getInstance().isAutoLogings()) {
            if (navFavListSimpleView != null) {
                navFavListSimpleView.onResponseError(new OnStarException("", mapActivity.getString(R.string.loading)));
            }
        }
        if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
            return false;
        }
        if (!BusinessUtil.checkPackageRight(Constants.ENTITLEMENT_M05NAVIGATION, mapActivity, true)) {
            return false;
        }
        //判断是否正在执行车辆的相关操作
        if (BusinessUtil.checkInProgressCommand(mapActivity, null, false)) {
            AlertDialogUtil.showAlertDialog(mapActivity, mapActivity.getString(R.string.dialog_warning),
                    mapActivity.getString(R.string.service_inProcess_alert));
//            BusinessUtil.updateConfigValue(FinalConfigParams.SHARE_DESTINATION, "-1", mapActivity);
            return false;
        }
        return true;
    }

    private void doNavCommand(final NavInfoModel navInfoModel) {
        BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Homesetting_clickfavorite_navigation.getStringValue());
        subscription = navService.doNavCommand(navInfoModel)
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String requestId) {
                        if (navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_NAV_DESTINATION || navInfoModel.remoteCommandsType == RemoteCommandsType.COMMANDS_TBT_ROUTE) {
                            saveHistoryToSql(requestId, navInfoModel.poiItemInfo, null, true);
                            //将下发历史保存到历史记录中
                            saveSearchHistory(navInfoModel.poiItemInfo);
                        }
                        if (navFavListSimpleView != null) {
                            navFavListSimpleView.showCommandLoading(true);
                        }
                        NavHolder.getInstance(mapActivity).setCurrentSendPoi(navInfoModel.poiItemInfo);

                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        if (navFavListSimpleView != null) {
                            navFavListSimpleView.onResponseError((OnStarException) throwable);
                        }
                    }
                });
    }

    public void saveHistoryToSql(String requestId, PoiItemInfo poiItemInfo, String status, boolean isSave) {
        PoiHistoryInfo historyInfo = new PoiHistoryInfo();
        historyInfo.setPoiItemInfo(poiItemInfo);
        if (isSave) {
            historyInfo.setStatus("inProgress");
        } else {
            historyInfo.setStatus(status);
        }
        TBTHistoryImpl impl = new TBTHistoryImpl(mapActivity);
        impl.saveOrUpdateModelDestinationHistory(requestId, historyInfo, isSave);
    }

    /**
     * @param
     * @return void
     * @Title: saveSearchHistory
     * @Description: 保存到历史记录中
     */
    public void saveSearchHistory(PoiItemInfo poiItemInfo) {
        SearchHistoryImpl impl = new SearchHistoryImpl(mapActivity);
        impl.saveSearchHistory(poiItemInfo);
        RxBus.getDefault().post(RxConstants.ALL_PAGE_REFRESH, RxConstants.NAV_SAVE_POI);

    }


    public void onItemClick(FavoriteEntity favoriteEntity) {
//        BusinessUtil.sendReportByClickType(mapActivity,
//                FunctionNameFindId.Searchpoi_clickfavorite.getStringValue());
        PoiItemInfo info = new PoiItemInfo();
        info.setTitle(favoriteEntity.getPoiName());
        info.setCityName(favoriteEntity.getCityCode());
        info.setCityCode(favoriteEntity.getPoiCityCode());
        info.setId(favoriteEntity.getFavoriteDestinationID());
        info.setLatitude(favoriteEntity.getPoiCoordinate().getLatitude());
        info.setLongitude(favoriteEntity.getPoiCoordinate().getLongitude());
        info.setAddress(favoriteEntity.getPoiAddress());
        info.setTelphone(favoriteEntity.getPoiPhoneNumber());
        info.setTypeDes(favoriteEntity.getPoiCatetory());

        String city = info.getCityName();
        if (DeviceUtil.getLanguage().equalsIgnoreCase("en")) {
            LoadCityList cityList = new LoadCityList(mapActivity);
            city = cityList.findByZhCity(info.getCityName());
        }
        info.setCityName(city);
    }


    public void submit(final PoiItemInfo poiItemInfo, final MapChoosePoiType mapChoosePoiType) {
//        if (CommonUtil.isNull(poiName) && CommonUtil.isNull(poiAddress)) {
//            if(navSetAddressView!=null) {
//                navSetAddressView.onResponseError(new OnStarException("",res.getString(R.string.nav_no_map_point)));
//            }
//        } else {
        // 点击确定返回到设置回家地址页面
        if (mapChoosePoiType == MapChoosePoiType.HOME || mapChoosePoiType == MapChoosePoiType.COMPANY) {
            subscription = navService.dosaveHomeOrCompanyAddressInfo(poiItemInfo, mapChoosePoiType)
                    .subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            if (mapChoosePoiType == MapChoosePoiType.HOME) {
                                userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "1");
                            } else if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
                                userAddressInfoImpl.saveUserAddressInfo(poiItemInfo, "2");
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            //里面抛出的Error信息
                            if (navFavListSimpleView != null) {
                                navFavListSimpleView.onResponseError((OnStarException) throwable);
                            }
                        }
                    });
        }
//        if (navFavListSimpleView != null) {
//            if (mapChoosePoiType == MapChoosePoiType.HOME) {
//                mapActivity.getNavDataHolder().setMapHomeChoosePoi(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.COMPANY) {
//                mapActivity.getNavDataHolder().setMapCompChoosePoi(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.START_POI) {
//                mapActivity.getNavDataHolder().setStartPoi(poiItemInfo);
//            } else if (mapChoosePoiType == MapChoosePoiType.END_POI) {
//                mapActivity.getNavDataHolder().setEndPoi(poiItemInfo);
//            }
//            navFavListSimpleView.onReponseSuccess(mapChoosePoiType);
//        }

        Intent intent = new Intent();
        SetAddressResult setAddressResult = new SetAddressResult();
        setAddressResult.mapChoosePoiType = mapChoosePoiType;
        setAddressResult.poiItemInfo = poiItemInfo;
        intent.putExtra("result",setAddressResult);
        mapActivity.setResult(1,intent);
        mapActivity.finish();
//        }
    }


    /**
     * pin码成功后回调
     *
     * @param
     */
    public void doGetFavList() {
        if (navFavListSimpleView != null) {
            navFavListSimpleView.setLoading(true);
        }
        subscription = navService.doGetFavList()
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<List<FavoriteEntity>>() {
                    @Override
                    public void call(List<FavoriteEntity> favoriteEntities) {
                        if (!CommonUtil.isNull(favoriteEntities) && favoriteEntities.size() > 0) {
                            if (navFavListSimpleView != null) {
                                navFavListSimpleView.setLoading(false);
                                navFavListSimpleView.showFavData(favoriteEntities);
                            }
                        } else {
                            navFavListSimpleView.setLoading(false);
                            navFavListSimpleView.showFavData(favoriteEntities);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        if (navFavListSimpleView != null) {
                            navFavListSimpleView.setLoading(false);
                            OnStarException onStarException = (OnStarException) throwable;
                            ErrorInfo errorInfo = ErrorCodeUtil.getErrorInfoByHttpException
                                    (mapActivity, new HttpException(onStarException.getErrorCode(), onStarException.getMessage()));
                            navFavListSimpleView.onResponseError(new OnStarException(errorInfo.getCode(), errorInfo.getMsg()));

                        }
                    }
                });
    }
}
